package com.witframework.web.tag;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.apache.commons.lang.StringUtils;

import com.witframework.util.BeanUtils;

public class ChooseNotEmptyTag extends TagSupport{
	private String parameter;
	private String defaultValue;
	@Override
	public int doStartTag() throws JspException {
		HttpServletRequest request=(HttpServletRequest)pageContext.getRequest();
		JspWriter writer = pageContext.getOut();
		String v="";
		String[] paras=StringUtils.split(parameter,";");
		for(String para:paras){
			v=request.getParameter(para);
			if(StringUtils.isEmpty(v)){
				String[] ovs=StringUtils.split(para,".");
				Object obj=null;
				for(int i=0;i<ovs.length;i++){
					if(i==0)
						obj=request.getAttribute(ovs[i]);
					else
						try {
							obj=BeanUtils.getDeclaredProperty(obj, ovs[i]);
						} catch (Exception e) {							
						}
				}
				if(null!=obj)
					v=String.valueOf(obj);
			}
			if(v!=null)
				break;
		}
		if(StringUtils.isEmpty(v)&&defaultValue!=null) 
			v=defaultValue;
		try {			
			writer.println(v);
		} catch (IOException e) {
			throw new JspException("Print/Flush in LoadingTag tag error:" + e);
		}
		return (EVAL_BODY_INCLUDE);
	}
	public void setParameter(String parameter) {
		this.parameter = parameter;
	}
	public void setDefaultValue(String defaultValue) {
		this.defaultValue = defaultValue;
	}
}
